package com.food.restaurantpro;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import com.food.restaurantpro.activity.MainActivity;
import com.food.restaurantpro.activity.SplashActivity;
import com.food.restaurantpro.connection.DataHelper;
import com.food.restaurantpro.imageloader.FileCache;
import com.food.restaurantpro.managingnetwork.ManagingNetwork;
import com.food.restaurantpro.objects.DishCategory;
import com.food.restaurantpro.objects.Food;
import com.food.restaurantpro.objects.PreOrderObject;
import com.food.restaurantpro.objects.Promotion;
import com.food.restaurantpro.objects.UserInfo;
import com.food.restaurantpro.observers.DishCategoryObserver;
import com.food.restaurantpro.observers.DishCategoryObserverInterface;
import com.food.restaurantpro.observers.FoodObserver;
import com.food.restaurantpro.observers.FoodObserverInterface;
import com.food.restaurantpro.observers.PlaceObserver;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class RestaurantApp extends Application  {

	public static Context CURRENT_CONTEXT;
	private static RestaurantApp _me;
	public static UserInfo userInfo;
	
	//list nay duoc khoi tao khi click order trong FoodGridViewFragment
	//va duoc dung trong MenuPreOrderFragment
	private ArrayList<Food> mFoodListForMenuPreOrder;
	//cai nay duoc khoi tao khi click gotoEditPreOrder trong YourPreOrderFragment
	//va duoc dung trong MenuPreOrderFragment
	private PreOrderObject mPreOrderObject;
	private boolean isPreOrderObject = false;
	public void setPreOrderObject(PreOrderObject preOrderObject) {
		isPreOrderObject = true;
		mPreOrderObject = preOrderObject;
	}
	
	public void setFoodList(ArrayList<Food> foodList) {
		isPreOrderObject = false;
		if(mFoodListForMenuPreOrder != null) {
			mFoodListForMenuPreOrder.clear();
			mFoodListForMenuPreOrder = null;
		}
		mFoodListForMenuPreOrder = foodList;
	}
	
	public boolean isPreOrderObject() {
		return isPreOrderObject;
	}
	
	public PreOrderObject getPreOrderObject() {
		return mPreOrderObject;
	}

	public ArrayList<Food> getFoodList() {
		return mFoodListForMenuPreOrder;
	}
	
	public RestaurantApp() {
		// TODO Auto-generated constructor stub
		super();
		CURRENT_CONTEXT = this;
		DataHelper.getInstance().deleteObservers();
		_me = this;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		userInfo = UserInfo.getCurrentUserInfo();
	}
	
	public static RestaurantApp getInstance() {
		return _me;
	}
	//use to download images of promotions
	private FileCache mFileCache;
	public void downloadBitmapToCache(final ArrayList<Promotion> promotionList, final SplashActivity splashActivity) {
		mFileCache = new FileCache(RestaurantApp.CURRENT_CONTEXT);
		
		//download images of promotions
		if(promotionList != null && promotionList.size() > 0 && ManagingNetwork.isNetworkAvailable()) {
			//Thread Download promotionImageSlide
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Download promotionImageSlide
					try {
						for (int i = 0; i < promotionList.size(); i++) {
							download(promotionList.get(i).getPromotionImageSlide());
						}
					} catch (Exception e) {
						// TODO: handle exception
						Log.e("RestaurantApp", "downloadBitmapToCache()", e);
					}
					
					//sau khi download xong images cua gallery thi open MainActivity
					splashActivity.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							startActivity(new Intent(splashActivity, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
							splashActivity.finish();
						}
					});
					
				}
			}).start();
			
			//Thread Download promotionImageMain
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Download promotionImageMain
					for (int i = 0; i < promotionList.size(); i++) {
						download(promotionList.get(i).getPromotionImageMain());
					}
				}
			}).start();
			
			//Thread Download promotionImageThumbnail
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Download promotionImageThumbnail
					for (int i = 0; i < promotionList.size(); i++) {
						download(promotionList.get(i).getPromotionImageThumbnail());
					}
				}
			}).start();
		} else {
			//neu danh sach promotion ko co update them
			splashActivity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					startActivity(new Intent(splashActivity, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
					splashActivity.finish();
				}
			});
		}
		
		updateFoods();
		updateDishCategory();
		new PlaceObserver();
	}
	
	private void download(String url) {
		try {
			File f = mFileCache.getFile(url);
			if(f.exists()) {
				return;
			}
			
			System.setProperty("http.keepAlive", "false");
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			// save file to m_FileCache
			copyStream(is, os);
			os.close();
		} catch (Throwable ex) {
			Log.e("RestaurantApp", "download() url = " + url, ex);
		}
	}
	
	private void copyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}
	//end download images of promotions
	
	private DishCategoryObserver mDishCategoryObserver;
	private void updateDishCategory() {
		mDishCategoryObserver = new DishCategoryObserver(
				new DishCategoryObserverInterface() {

					@Override
					public void dishCategoryCallback(
							final ArrayList<DishCategory> dishCategoryList,
							String messageError) {
						// TODO Auto-generated method stub
						
						//download images of dish category
						if(dishCategoryList != null && dishCategoryList.size() > 0 && ManagingNetwork.isNetworkAvailable()) {
							new Thread(new Runnable() {
								
								@Override
								public void run() {
									// TODO Auto-generated method stub
									for (int i = 0; i < dishCategoryList.size(); i++) {
										download(dishCategoryList.get(i).getDishCategoryImage());
									}
								}
							}).start();
						}
					}
				});
		mDishCategoryObserver.registerObserver();
	}
	
	private FoodObserver mFoodObserver;
	private void updateFoods() {
		mFoodObserver = new FoodObserver(new FoodObserverInterface() {
			
			@Override
			public void foodListCallback(final ArrayList<Food> foodList, String messageError) {
				// TODO Auto-generated method stub
				if(foodList != null && foodList.size() >0 && ManagingNetwork.isNetworkAvailable()) {
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							for (int i = 0; i < foodList.size(); i++) {
								download(foodList.get(i).getFoodImage());
							}
						}
					}).start();
				}
			}
		});
		mFoodObserver.registerObserver();
	}
}
